package internationalenergytradingplatform.controller.SupplierController;


import internationalenergytradingplatform.context.BaseContext;
import internationalenergytradingplatform.dao.ClassificationDao;
import internationalenergytradingplatform.dao.CommodityDao;
import internationalenergytradingplatform.dto.CommodityPageQueryDTO;
import internationalenergytradingplatform.dto.EmployeePageQueryDTO;
import internationalenergytradingplatform.pojo.Classification;
import internationalenergytradingplatform.pojo.Commodity;
import internationalenergytradingplatform.result.PageResult;
import internationalenergytradingplatform.result.Result;
import internationalenergytradingplatform.service.ExcelService;
import internationalenergytradingplatform.service.SupplierCommodityService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/commodity")
@CrossOrigin
@Slf4j
public class CommodityController {

    @Autowired
    SupplierCommodityService supplierCommodityService;

    @Autowired
    ClassificationDao classificationDao;

    @Autowired
    CommodityDao commodityDao;

    @Autowired
    ExcelService excelService;

    /**
     *
     * @author yingfeng
     * @date 2024/3/4 21:40
     商品分页查询
     */
    @GetMapping("/paginationQuery")
    public Result<PageResult> pagingToQueryAllCommodity(CommodityPageQueryDTO commodityPageQueryDTO){
        log.info("商品分页查询，参数为：{}", commodityPageQueryDTO);
        PageResult pageResult = supplierCommodityService.pageQuery(commodityPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/12 14:46
     类别查询（根据供应商）
     */
    @GetMapping("/getAllClassificationByTele")
    public Result<PageResult> getAllClassificationByTele(){
        String companyId = BaseContext.getCurrentId();//获取公司id
        List<Classification> allClassificationByTele = classificationDao.getAllClassificationByTele(companyId);
        PageResult pageResult = new PageResult(allClassificationByTele.size(), allClassificationByTele);
        return Result.success(pageResult);
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/12 14:46
    类别查询
     */
    @GetMapping("/getAllClassification")
    public Result<PageResult> getAllClassification(){

        List<Classification> allClassification = classificationDao.getAllClassification();
        PageResult pageResult = new PageResult(allClassification.size(), allClassification);
        return Result.success(pageResult);
    }


    /**
     *
     * @author yingfeng
     * @date 2024/3/12 16:20
     上架/下架
     */
    @PutMapping("/putUpOrDown/{id}/{status}")
    public Result<?> putUpOrDown(@PathVariable Integer id, @PathVariable Integer status){
        commodityDao.listingProducts(id, status);
        return Result.success();
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/12 17:29
     新增商品
     */
    @PostMapping("/newProductsAdd")
    public Result<?> newProductsAdd(@RequestBody Commodity commodity){
        if(commodity.getClassification() == null){
            commodity.setClassification(5);
        }
        commodity.setCommodityStatus(1);
        String companyId = BaseContext.getCurrentId();//获取公司id
        commodity.setSupplierAccount(companyId);
        commodityDao.addCommodity(commodity);
        return Result.success();

    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteCommodity(@PathVariable Integer id){
        commodityDao.deleteCommodity(id);
        return Result.success();
    }

    /**
     * 修改商品
     */
    @PutMapping("/modify")
    public Result<?> modifyCommodity(@RequestBody Commodity commodity){
        log.info("修改商品：{}", commodity);
        commodityDao.modifyCommodity(commodity);
        return Result.success();
    }

    /**
     * 根据id查找商品
     */
    @GetMapping("/findById/{id}")
    public Result<Commodity> getCommodityById(@PathVariable Integer id){
        Commodity commodityById = commodityDao.getCommodityById(id);
        log.info("根据id查找商品:{}", commodityById);
        return Result.success(commodityById);
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/15 15:26
     批量增加商品
     */
    @PostMapping("/upload-excel")
    public Result<?> uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty() || file.getSize() == 0) {
            return Result.error("File is empty or invalid");
        }

        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            return  Result.error("File is not an excel file");
        }


        try {
            List<Commodity> commodities = excelService.readExcelFile(file);
            for (Commodity commodity : commodities) {
                commodityDao.addCommodity(commodity);
            }

            // Return the result
            return Result.success();
        } catch (Exception e) {
            // Handle exceptions and return an appropriate error message
            return Result.error("Error occurred while processing the file: " + e.getMessage());
        }
    }
}
